import { defaultParentID } from '@/config';
import api from '@/pages/Goods/ClassifyManagement/request';
import { requestConfig } from '@/services/config';
import { PlusOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ProFormSlider,
  ProFormSwitch,
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form, message } from 'antd';
import { useState } from 'react';
export type Data = GoodsClassifyManagementApi.InfoResponse;
export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: Data;
  onSuccess?: () => void;
  onCancel?: () => void;
}
function GoodsClassifyManagementForm(props: Props) {
  const { data, isEdit = false } = props;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({});
  const [fileList, setFileList] = useState<any[]>([]);
  const [info, setInfo] = useState<Partial<GoodsClassifyManagementApi.InfoResponse>>({});

  const onOpenChange = (open: boolean) => {
    if (open) {
      const info: any = data
        ? isEdit
          ? data
          : { id: '', parentId: data.id }
        : { parentId: defaultParentID };
      setInfo(info);
      form.setFieldsValue(info);
      setFormData(info);
      if (info.classifyIcon) {
        setFileList([
          {
            uid: '',
            name: info.classifyIcon,
            url: `${requestConfig.imageURL}${info.classifyIcon}`,
          },
        ]);
      }
    } else {
      setInfo({});
      form.resetFields();
      setFormData({});
      setFileList([]);
      props.onCancel?.();
    }
  };
  const onSubmit = async () => {
    const { classifyName, classifyIcon, orderNo, isRecommend } = formData;
    const { id = '', parentId = '' } = info;
    if (isEdit) {
      const params: GoodsClassifyManagementApi.UpdateParams = {
        id,
        parentId,
        classifyName,
        classifyIcon,
        orderNo,
        isRecommend,
      };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: GoodsClassifyManagementApi.CreateParams = {
        parentId,
        classifyName,
        classifyIcon,
        orderNo,
        isRecommend,
      };
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}分类`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <Button type="link">新建</Button>
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <ProFormText
        required
        name="classifyName"
        label="分类名称"
        placeholder="请输入分类名称"
        fieldProps={{
          value: formData.classifyName,
          onChange: (e) => setFormData({ ...formData, classifyName: e.target.value }),
        }}
      />
      <ProFormUploadButton
        required
        name="classifyIcon"
        label="分类图片"
        placeholder="请上传图片"
        max={1}
        action={requestConfig.uploadURL}
        fieldProps={{
          name: 'files',
          listType: 'picture-card',
          headers: { Authorization: `Bearer ${window.localStorage.getItem('access_token')}` },
          fileList: fileList,
          onChange: (info) => {
            const isLt50M = (info.file.size || 0) / 1024 / 1024 < 50;
            if (isLt50M) {
              let fileList = [...info.fileList];
              if (fileList.length > 1) {
                fileList = fileList.splice(0, fileList.length - 1);
              }
              setFileList(fileList);
            } else {
              setFileList([]);
            }
            if (info.file.status === 'removed') {
              setFormData({ ...formData, classifyIcon: '' });
            } else if (info.file.status === 'done') {
              if (info?.file?.response) {
                if (info?.file?.response?.failed) {
                  info.file!.status = 'error';
                  return message.warning(info?.file?.response?.message);
                } else if (info?.file?.response?.status === 500) {
                  info.file!.status = 'error';
                  return message.warning('上传失败');
                }
                const { uploadedFiles = [] } = info.file.response;
                const classifyIcon = uploadedFiles && uploadedFiles.length ? uploadedFiles[0] : '';
                setFormData({ ...formData, classifyIcon });
              }
            }
          },
        }}
      />
      <ProFormSwitch
        required
        name="isRecommend"
        label="推荐"
        placeholder="请选择推荐"
        fieldProps={{
          checked: formData.isRecommend,
          onChange: (value) => {
            setFormData({ ...formData, isRecommend: value });
          },
        }}
      />
      <ProFormSlider
        required
        name="orderNo"
        label="排序"
        placeholder="请输入排序"
        fieldProps={{
          value: formData.orderNo,
          onChange: (value: number) => {
            setFormData({ ...formData, orderNo: value });
          },
        }}
      />
    </DrawerForm>
  );
}

export default GoodsClassifyManagementForm;
